package com.huahai.exception;

import com.huahai.common.BaseResponse;
import com.huahai.common.ErrorCode;
import com.huahai.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("businessException: " + e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage(), e.getDescription());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("runtimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage(), "");
    }

    // 处理SQL语法错误
    @ExceptionHandler(BadSqlGrammarException.class)
    public BaseResponse<Void> handleBadSqlGrammarException(BadSqlGrammarException e) {
        log.error("数据库SQL错误:", e); // 日志记录详细错误
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统维护中，请稍后重试"); // 前端友好提示
    }
}
